package cn.lingyangwl.agile.msg.push.api.utils;

import cn.lingyangwl.agile.msg.push.api.constatnts.ChannelTypeEnum;
import cn.lingyangwl.agile.msg.push.api.constatnts.StaticService;
import cn.lingyangwl.agile.msg.push.api.model.content.MsgParam;
import cn.lingyangwl.agile.msg.push.api.model.rqrs.MsgPushParam;
import cn.lingyangwl.framework.tool.core.exception.BizException;
import org.apache.commons.lang3.StringUtils;

import java.util.Objects;

/**
 * 消息推送工具类
 * @author shenguangyang
 */
public class MsgPushUtils {

    /**
     * 推送消息(实时推送)
     *
     * @param content       消息内容实体
     * @param toUsers 接受者用户编码，多个用逗号隔开，可直接指定接受者手机号或邮箱地址或者微信的openid等
     * @author ThinkGem
     */
    public static void push(ChannelTypeEnum channelType, MsgParam content, String toUsers) {
        push(channelType, false, content, toUsers);
    }

    /**
     * 推送消息(异步推送), 走消息队列
     *
     * @param content       消息内容实体
     * @param toUsers 接受者用户编码，多个用逗号隔开，可直接指定接受者手机号或邮箱地址或者微信的openid等
     * @author ThinkGem
     */
    public static void pushAsync(ChannelTypeEnum channelType, MsgParam content, String toUsers) {
        push(channelType, true, content, toUsers);
    }

    /**
     * 推送消息
     *
     * @param isAsync          是否异步推送
     * @param toUsers 接受者用户编码，多个用逗号隔开，可直接指定接受者手机号或邮箱地址或者微信的openid等
     * @author ThinkGem
     */
    public static void push(ChannelTypeEnum channelType, boolean isAsync, MsgParam content, String toUsers) {
        toUsers = StringUtils.defaultIfEmpty(toUsers, "none");
        if (Objects.isNull(channelType)) {
            throw new BizException("渠道类型不能为空");
        }
        boolean isNone = StringUtils.startsWith(toUsers, "[CODE]");
        if (isNone) {
            toUsers = StringUtils.substringAfter(toUsers, "[CODE]");
        }
        for (String toUser : StringUtils.split(toUsers, ",")) {
            content.setToUser(toUser);
            MsgPushParam pushParam = new MsgPushParam();
            pushParam.setChannelType(channelType.getCode());
            pushParam.setMsgParam(content);
            if (isAsync) {
                StaticService.msgPushAsyncHandler().push(pushParam, content.getPlanPushDate());
            } else {
                StaticService.msgPushApi().push(pushParam);
            }
        }
    }

}
